package com.strongbj.iot.devices.newlight.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.common.Executer;
import com.strongbj.iot.devices.newlight.entity.Tag;
import com.strongbj.iot.devices.newlight.entity.TagBind;
import com.strongbj.iot.devices.newlight.message.NewLightMQMessage;
import com.strongbj.iot.devices.newlight.message.NewLightReaderMessage;
import com.strongbj.iot.devices.newlight.response.common.HandleTimeStamp;
import com.strongbj.iot.devices.newlight.service.TagService;
import com.strongbj.iot.mq.producer.TopicSender;

import cn.hutool.core.date.DateUtil;
import io.netty.channel.ChannelHandlerContext;

/**
 * 类型码：0x02，标签绑定确认
 * 
 * @author lei_w
 *
 */
public class LabelBindingResponseHandle implements IMessageHandle<NewLightReaderMessage, Object> {

	private static Logger logger = LogManager.getLogger(LabelBindingResponseHandle.class.getName());

	private TagService tagService = (TagService) ContextUtils.getBean("tagService");
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

	@Override
	public boolean isHandle(NewLightReaderMessage t) {
		if (Integer.valueOf("2", 16).byteValue() == t.getType()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightReaderMessage t) {
		// 判断返回消息是否和当前执行命令序列号一致
		if (ByteUtil.byteArrayToInt(t.getTime()) == Executer.currentSequence) {
			Executer.currentThread.stop();
		}
		System.out.println("返回报文--" + ByteUtil.byteArrToHexString(t.getBody()));
		String hostNumber = ByteUtil.bytesToAddress(t.getAddress()); // reader 地址码
		String timeStamp = ByteUtil.byteArrToHexString(t.getTime()); // 时间戳
		// 4 字节标签地址 + 2 字节标签短地址 + 2 字节标签信息（参考 LED 标签信息格 式，下同） + 保留字段。
		// String tagAddress = ByteUtil.byteArrToHexString(t.getBody(), 0, 4); // LED
		// 标签地址
		String tagAddress = ByteUtil.bytesToIp(ByteUtil.subBytes(t.getBody(), 0, 4));// LED 标签地址
		String shortAddress = ByteUtil.byteArrToHexString(t.getBody(), 4, 2); // 签短地址
		String tagState = ByteUtil.byteToBitString(ByteUtil.subBytes(t.getBody(), 6, 1)[0]); // 标签其他状态
		String powerState = tagState.substring(5, 8);
		String fbState = tagState.substring(3, 5);
		String fsState = tagState.substring(2, 3);
		String ledState = ByteUtil.byteToBitString(ByteUtil.subBytes(t.getBody(), 7, 1)[0]); // 标签LED状态
		String led1State = ledState.substring(6, 8);
		String led2State = ledState.substring(4, 6);
		String led3State = ledState.substring(2, 4);
		String led4State = ledState.substring(0, 2);

		String log = "\r\n===================================================" + "\r\n收到标签绑定确认返回报文：" + "\r\nREADER地址码： "
				+ hostNumber + "\r\nLED标签地址： " + tagAddress + "\r\n短地址 ： " + shortAddress + "\r\n标签电量状态：  " + powerState
				+ "\r\n功能按键状态：  " + fbState + "\r\n防撕状态：" + fsState + "\r\nLED1状态：" + led1State + "\r\nLED2状态："
				+ led2State + "\r\nLED3状态：" + led3State + "\r\nLED4状态：" + led4State + "\r\n时间戳：   "
				+ HandleTimeStamp.handle(timeStamp) + "\r\n===================================================";
		logger.info(log);
		Tag tag = new Tag();
		tag.setIp(tagAddress);
		tag.setShortAddress(shortAddress);
		tag.setReader(hostNumber);
		tag.setState(1);
		tagService.updateById(tag);

		NewLightMQMessage mes = new NewLightMQMessage();
		mes.setActioncode("bindTag");
		mes.setGUID(String.valueOf(DateUtil.date().getTime()));
		TagBind tb = new TagBind();
		tb.setReaderCode(hostNumber);
		tb.setTag(tagAddress);
		tb.setBindSuccess(!"0000".equals(shortAddress));
		mes.setPostdata(tb);
		topicSender.send("wh.reader." + hostNumber + ".message", JSON.toJSONString(mes));
		logger.info("=========bindTag=======" + JSON.toJSONString(mes));
		return null;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub

	}

}
